package obs;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.*;

public class ManySocketv2 {
    public static void main(String[] args) {

    }
}

class ManySCV2 {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(
                new InetSocketAddress("master",1111));
        socketChannel.configureBlocking(true);


        new Thread(() -> {
            while (true){
                ByteBuffer buffer = ByteBuffer.allocate(128);
                int limit = 0;
                try {
                    limit = socketChannel.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("读到的长度"+limit);
                buffer.flip();
                String s = new String(buffer.array(), 0, limit, StandardCharsets.UTF_8);
                ManySocketV1.debug("读到的信息 " + s);
            }

        }, "client-listen").start();

        Scanner scanner = new Scanner(System.in);
        while (true) {
            String s = scanner.nextLine();
            if (s.contains("=") && s.contains(":")) {
                ByteBuffer ss = ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8));
                while (ss.hasRemaining()){
                    System.out.println(new String(ss.array()));
                    socketChannel.write(ss);
                }

            } else {
                ManySocketV1.debug("格式不符合 " + s);
            }


        }
        //开启监听函数子线程，不过该线程目前不会读到任何消息，因为还没有订阅主题}
        //链接失败回调函数

    }
}

class ManySSV2{

//    public static ExecutorService writerEs = Executors.newFixedThreadPool(3);
//    待广播的消息缓存队列
    public static LinkedBlockingQueue<String> infos = new LinkedBlockingQueue();
//    待广播的对象列表，这里加了额外加了频道
    public static Map<String ,Set<SelectionKey>> audiances = new ConcurrentHashMap<>();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();

        serverChannel.bind(new InetSocketAddress(1111));

        serverChannel.configureBlocking(true);
//        CopyOnWriteArrayList<Selector> selectors = new CopyOnWriteArrayList<>();
        Selector listenManager = Selector.open();

        new Thread(()->{
            ManySocketV1.debug("开始监听的消息");
            while (true){
                try {
                    System.out.println("gogogo");
                    int select = listenManager.select(5000);

                    System.out.println(select);
                    if (select==0) continue;
                    ManySocketV1.debug("貌似监听到一个或多个消息");
                    Iterator<SelectionKey> iterator = listenManager.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        try{
                            SelectionKey s = iterator.next();

                            if (s.isValid()&& s.isReadable()){
                                SocketChannel ss= (SocketChannel) s.channel();
                                ByteBuffer buffer = ByteBuffer.allocate(128);
                                int length = ss.read(buffer);
                                buffer.flip();
                                String msg = new String(buffer.array(), 0, length, StandardCharsets.UTF_8);
                                ManySocketV1.debug("读到的消息"+msg);
                            }
                        }finally {
                            iterator.remove();
                        }
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        },"唯一一个读线程").start();

        while (true){
            SocketChannel clientChannel = serverChannel.accept();
            clientChannel.configureBlocking(false);
            ManySocketV1.debug(clientChannel.getLocalAddress()+" "+clientChannel.getRemoteAddress());
            SelectionKey superChannel = clientChannel.register(listenManager, SelectionKey.OP_READ);
//            superChannel.selector().wakeup();
            ManySocketV1.debug(superChannel);

        }

    }
}

